// pages/mine/index.js
const app = getApp()
Page({
	data: {
		user: undefined,
		url: app.globalData.url,
	},
	// 用户登录
	to_login() {
		wx.showLoading({
		  title: '请稍后',
		})
		const appid = "wx8efd630c320af804"
		const secret = "1174ac6e704e3ca93e12eb5b5eeec336"
		const that = this
		wx.login({
			success(res) {
				if (res.code) {
					// 将登录凭证发送到服务端
					wx.request({
						url: 'https://api.weixin.qq.com/sns/jscode2session?appid='
							+ appid + '&secret=' + secret + '&js_code=' + res.code
							+ '&grant_type=authorization_code',
						method: 'GET',
						success(res) {
							wx.request({
								url: that.data.url + "/user/login",
								data: {
									openid: res.data.openid
								},
								success(res) {
									if (res.data.code == 1) {
										console.log(res.data.result);
										wx.setStorageSync("user", res.data.result)
										that.setData({ user: res.data.result })
										wx.showToast({ title: '登录成功' })
										const pages = getCurrentPages()
										const perpage = pages[pages.length - 1]
										perpage.onLoad()
										wx.hideLoading({
										  success: (res) => {},
										})
									}
								}
							})
						}
					})
				}
			}
		})
	},
	onShow() {
		const user = wx.getStorageSync("user")
		if (user) {
			this.setData({ user })
		}
	},
	// 地址管理
	address() {
		wx.navigateTo({
			url: '/pages/address/index',
		})
	},
	accountinfo() {
		const that = this
		wx.navigateTo({
			url: '/pages/account/index?user=' + JSON.stringify(this.data.user),
		})
	},
	// 订单管理
	orders(e) {
		wx.navigateTo({
			url: '/pages/orders/index?item=' + e.currentTarget.dataset.item,
		})
	}
})